import React, { isValidElement } from 'react';
import { Col, DatePicker, Form, type FormInstance, Input, Row, Select } from 'antd';
import type { DictType } from '@/components/DictTag';
import type { ReactElement } from 'react';

type NodeType = 'input' | 'select' | 'date-picker';
type ItemType = {
	type?: NodeType;
	name: string;
	label?: string;
	colspan?: number;
	options?: DictType[];
	// custom?: ReactElement;
};
export type ItemConfigType = (ItemType | ReactElement)[][];
type MainPropsType = {
	form: FormInstance;
	config: ItemConfigType;
	labelWidth?: number;
};

const FormPro = (props: MainPropsType) => {
	const { form, config, labelWidth } = props;

	return (
		<Form form={form} labelCol={{ style: { width: labelWidth ? labelWidth + 'px' : 'auto' } }}>
			<Row>
				{config.map((rowItem) => {
					const colSpan = Math.ceil(24 / rowItem.length);
					return rowItem.map((formItem, index) => {
						if (isValidElement(formItem)) {
							// return React.cloneElement(formItem, { key: index });
							return (
								<Col key={index} span={colSpan}>
									{formItem}
								</Col>
							);
						} else {
							let node = null;
							switch (formItem.type) {
								case 'select':
									node = <Select placeholder="请选择" options={(formItem as ItemType).options} />;
									break;
								case 'date-picker':
									node = <DatePicker placeholder="请选择" style={{ width: '100%' }} />;
									break;
								default:
									node = <Input placeholder="请输入" />;
							}
							return (
								<Col
									key={(formItem as ItemType).name}
									span={(formItem as ItemType).colspan ?? colSpan}
								>
									<Form.Item
										name={(formItem as ItemType).name}
										label={(formItem as ItemType).label}
									>
										{node}
									</Form.Item>
								</Col>
							);
						}
					});
				})}
			</Row>
		</Form>
	);
};

export default FormPro;
